package es.innova_t.android.pepe;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AndroidGalleryActivity extends Activity {
	
	private long selectedImage;
	private List<ImageView> lImage = new ArrayList<ImageView>();
	private List<ContactDTO> lDTO = new ArrayList<ContactDTO>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	    LinearLayout gallery = (LinearLayout) findViewById(R.id.gallery);
	    lDTO = getContacts();
	    for(int i=0;i<lDTO.size();i++){
	    	LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(500, 700);
	    	LinearLayout grid = new LinearLayout(this);
	    	grid.setOrientation(LinearLayout.VERTICAL);
	    	grid.setGravity(Gravity.CENTER);
	    	ContactDTO cDTO = lDTO.get(i);
	    	ImageView iView = new ImageView(this);
	    	iView.setImageBitmap(cDTO.getContactImage());
	    	iView.setId(i);
	    	registerForContextMenu(iView);
	    	lImage.add(iView);
	    	grid.addView(iView);
	    	TextView name = new TextView(this);
	    	name.setText("Name: " + cDTO.getName());
	    	name.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
	    	grid.addView(name);
	    	TextView number = new TextView(this);
	    	String num = cDTO.getPhoneNumerDTO().get(0).getNumber();
	    	number.setText("Number: "+ num);
	    	number.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
	    	grid.addView(number);
	    	gallery.addView(grid,p);
	    }
	}
	
    private void call(String number) {
        try {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:"+number));
            startActivity(callIntent);
        } catch (ActivityNotFoundException e) {
            Log.e("helloandroid dialing example", "Call failed", e);
        }
    }
    
    private void sendSMS(String number){
    	startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));
    }

	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	                                ContextMenuInfo menuInfo)
	{
		selectedImage = v.getId();
		menuInfo = new AdapterView.AdapterContextMenuInfo(v,0,v.getId());
	    super.onCreateContextMenu(menu, v, menuInfo);
	 
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		ContactDTO contact = lDTO.get((int)selectedImage);
		String number = contact.getPhoneNumerDTO().get(0).getNumber();
//		String name = contact.getName();
	    switch (item.getItemId()) {
	        case R.id.phone:
	            call(number);
	            return true;
	        case R.id.sendSMS:
	        	sendSMS(number);
	            return true;
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
//	
	
	private List<ContactDTO> getContacts(){
		List<ContactDTO>l=new ArrayList<ContactDTO>();
		
		List<Integer>lContacts = getListContacts();
		
		for(int i=0;i<lContacts.size();i++){
			Integer contactId = lContacts.get(i);
			String name = getContactName(contactId);
			List<PhoneNumberDTO> lPhoneNumer = getContactPhoneNumbers(contactId);
			String photoId = getContactPhotoId(contactId);
			Bitmap bitmap = getContactPhoto(photoId);
			
			ContactDTO contactDTO = new ContactDTO();
			contactDTO.setContactImage(bitmap);
			contactDTO.setName(name);
			contactDTO.setPhoneNumerDTO(lPhoneNumer);
			l.add(contactDTO);
		}
		
		return l;
		
	}
	
	private List<Integer> getListContacts(){
		List<Integer> lContactId = new ArrayList<Integer>();
		String[] projection = new String[] {
				RawContacts.CONTACT_ID // the contact id column
				};
		
		Cursor rawContacts = managedQuery(
					RawContacts.CONTENT_URI,    // the URI for raw contact provider
					projection,
					null,                   // selection = null, retrieve all entries
					null,                   // selection is without parameters
					null);                  // do not order
		
		int contactIdColumnIndex = rawContacts.getColumnIndex(RawContacts.CONTACT_ID);
	
		if(rawContacts.moveToFirst()) {
			    while(!rawContacts.isAfterLast()) {     // still a valid entry left?
			        int contactId = rawContacts.getInt(contactIdColumnIndex);
			        lContactId.add(contactId);
			        rawContacts.moveToNext();           // move to the next entry
			    }
		}
		return lContactId;				
	}
	
	private String getContactPhotoId(Integer contactId){
		Log.i("Image", "contactId: " + contactId);
		String[] projection = new String[] {
			    Contacts.PHOTO_ID       // the id of the column in the data table for the image
			};

		Cursor contact = managedQuery(
	        Contacts.CONTENT_URI,
	        projection,
	        Contacts._ID + "=?",    // filter entries on the basis of the contact id
	        new String[]{String.valueOf(contactId)},    // the parameter to which the contact id column is compared to
	        null);
		
		if(contact.moveToFirst()) {
		    String photoId = contact.getString(
		            contact.getColumnIndex(Contacts.PHOTO_ID));
		    return photoId;
		}
				contact.close();
		return null;

	}
	
	private String getContactName(Integer contactId){
		String[] projection = new String[] {
		    Contacts.DISPLAY_NAME  // the name of the contact
		};
		
		Cursor contact = managedQuery(
            Contacts.CONTENT_URI,
            projection,
            Contacts._ID + "=?",    // filter entries on the basis of the contact id
            new String[]{String.valueOf(contactId)},    // the parameter to which the contact id column is compared to
            null);
		
		if(contact.moveToFirst()) {
			String name = contact.getString(
		    contact.getColumnIndex(Contacts.DISPLAY_NAME));
		    return name;
		}
		contact.close();
		return null;
		
	}
	
	private Bitmap getContactPhoto(String photoId){
		Log.i("Image", "photoId: " + photoId);
		if (photoId != null){
			Cursor photo = managedQuery(
		        Data.CONTENT_URI,
		        new String[] {Photo.PHOTO},     // column for the blob
		        Data._ID + "=?",                // select row by id
		        new String[]{photoId},          // filter by photoId
		        null);
			if(photo.moveToFirst()) {
			    byte[] photoBlob = photo.getBlob(
			            photo.getColumnIndex(Photo.PHOTO));
			    Bitmap photoBitmap = BitmapFactory.decodeByteArray(
			            photoBlob, 0, photoBlob.length);
			    return photoBitmap;
			}
			photo.close();
		}
		return null;
	}
	
	private List<PhoneNumberDTO> getContactPhoneNumbers(Integer contactId){
		List<PhoneNumberDTO> nums = new ArrayList<PhoneNumberDTO>();
		String[] projection = new String[] {
	        Phone.NUMBER,
	        Phone.TYPE,
		};
		Cursor phone = managedQuery(
			Phone.CONTENT_URI,
            projection,
            Data.CONTACT_ID + "=?",
            new String[]{String.valueOf(contactId)},
            null);
		
		if(phone.moveToFirst()) {
		    int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
		    int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
		 
		    while(!phone.isAfterLast()) {
		        String number = phone.getString(contactNumberColumnIndex);
		        int type = phone.getInt(contactTypeColumnIndex);
		        int typeLabelResource = Phone.getTypeLabelResource(type);
		        PhoneNumberDTO pn = new PhoneNumberDTO();
		        pn.setLabelResourceType(typeLabelResource);
		        pn.setNumber(number);
		        nums.add(pn);
		        phone.moveToNext();
		    }
		 
		}
		phone.close();
		return nums;
	}
	
	
}